use std::borrow::BorrowMut;
use std::future::{ready, Ready};
use std::fmt::Debug;
use actix_web::dev::Url;
use actix_web::{HttpResponse, HttpMessage};
use actix_web::body::{MessageBody, BoxBody};
use actix_web::cookie::Cookie;
use actix_web::http::header::HeaderValue;
use actix_web::http::{StatusCode, header, Uri};
use actix_web::{
    dev::{forward_ready, Service, ServiceRequest, ServiceResponse, Transform},
    Error,
};
use futures_util::future::LocalBoxFuture;

//: 挂载在 cs 区

// 中间件处理有两个步骤。
// 1. 中间件初始化，中间件工厂被调用
// 链中的下一个服务作为参数。
// 2. 中间件的调用方法被正常请求调用。
pub struct Example{
    code:u16
}
impl Example {
    pub fn new(code:u16)->Example{
        Example { code }
    }
}

// 中间件工厂是 `Transform` trait
// `S` - 下一个服务的类型
// `B` - 响应正文的类型
impl<S> Transform<S, ServiceRequest> for Example
where
    S: Service<ServiceRequest, Response = ServiceResponse, Error = Error>,
    S::Future: 'static,
{
    type Response = ServiceResponse;
    type Error = Error;
    type InitError = ();
    type Transform = ExampleMiddleware<S>;
    type Future = Ready<Result<Self::Transform, Self::InitError>>;

    fn new_transform(&self, service: S) -> Self::Future {
        ready(Ok(ExampleMiddleware { service ,code:self.code}))
    }
}

pub struct ExampleMiddleware<S> {
    service: S,
    code:u16
}

impl<S> Service<ServiceRequest> for ExampleMiddleware<S>
where
    S: Service<ServiceRequest, Response = ServiceResponse, Error = Error>,
    S::Future: 'static,
{
    type Response = ServiceResponse;
    type Error = Error;
    type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;

    forward_ready!(service);

    fn call(&self, mut req: ServiceRequest) -> Self::Future {
        // println!("{:#?}",req);
        // println!("{:#?}",req.match_info());

        // req.match_info_mut().set(Url::new(Uri::try_from("/cs")
        //     .unwrap()));
        // req.match_info_mut().skip(3);
        // // req.head_mut().uri = Uri::try_from("/cs").unwrap();

        // println!("{:#?}",req.match_info());
        // println!("{:#?}",req);
        
        let fut = self.service.call(req);
        let code = self.code;
        Box::pin(async move {
            let mut res = fut.await?;
            
            let (req,res) = res.into_parts();
            if code.eq(&res.status().as_u16()) {
                println!("Example(middleware)产生效果:{}",code);
            }

            Ok(ServiceResponse::new(req, res))
        })
    }
}
